;(function($){
	var main = function(){
		var dish = $(".one-dish").eq(0);
		var fix = $(".shop-category").eq(0);
		var fixclone;
		var ftop = fix.offset().top;
		var onscroll;
		var topoffs;
		var shopid = GetShopid();
		var btnjoincart = $('<button class="cartbutton joincart">加入购物车</button>');
		var btnspec = $('<button class="cartbutton selectspec">选规格</button>');
		var btnmodnum = $('<div class="cartbutton num-modifier"><button class="minus">-</button><input type="text" class="inputnumber" value="1"  size="2"/><button class="plus">+</button></div>');
		var speclist;
		var curspec;
		var cartitem = $('<div class="cart-item" goodsid="" style="height:44px"><div class="cart-item-wrapper"><span class="cart-item-name">桂花鸡蛋仔</span><div class="num-modifier" ><button class="minus">-</button><input type="text" class="number" value="1" /><button class="plus">+</button></div><span class="price"><i class="icon-cny"></i>14</span></div></div>');
		var sspec = $(".s-spec");
		var goodsdata;
		
		function findSpec(specno){
			if(curspec){
				return curspec.find(function(a){
					return a.specno == specno;
				});
				
			}
		}
		
		function GetShopid()
		{
		     var reg = new RegExp("(^|&)shopid=([^&]*)(&|$)");
		     var r = window.location.search.substr(1).match(reg);
		     if(r!=null)return  parseInt(unescape(r[2])); return null;
		}
		
		var validateShopGuideHover = function(){
			$(".shop-guide-extra").stop(true).slideUp(0);
			$(".shop-guide-info").hover(
				function(){
					$(".shop-guide-extra").stop(true).slideDown(50);
				},
				function(){
					$(".shop-guide-extra").stop(true).slideUp(50);
				}
			);
		}
		
		var validateDescHover = function(){
			var tooltip; 
			dish.find(".dish-desc").hover(
				function(){
					tooltip = $(this).parent().find(".more-desc").eq(0);
					tooltip.stop(true).fadeIn(300);
				}
				,function(){
					tooltip = $(this).parent().find(".more-desc").eq(0);
					tooltip.stop(true).fadeOut(100);
				});
		}
		
		var validateShowTipHover = function(){
			var showtip = $(".showtip");
			showtip.hover(
				function(){
					$(this).find(".tooltip").eq(0).stop(true).fadeIn(300);
				},
				function(){
					$(this).find(".tooltip").eq(0).stop(true).fadeOut(100);
				}
				)
		}
	
		//ajax调用方
		var requestGoods = function(){
			var req = {"shopid": shopid};  
//			在上面构造需要发到服务器的JSON
			$.ajax({
				type:"post",
				url:"shopmenu",
				data:req,
				dataType: "JSON",
				scriptCharset: 'utf-8', 
				success: goodsLoader
			});
		}
		
		var requestMenu = function(){
			var req = {"shopid": shopid}; 
			$.ajax({
				type:"post",
				url:"menucate",
				data:req,
				dataType: "JSON",
				scriptCharset: 'utf-8', 
				success: menuLoader
			})
		}
		
		var requestSpec = function(){
			var req = {"shopid": shopid};
			$.ajax({
				type:"post",
				url:"specloader",
				data:req,
				dataType: "JSON",
				scriptCharset: 'utf-8', 
				success: function(data){
					speclist = data;
				}
			})		
		}
		
		//回调函数
		
		var goodsLoader = function(data){
			var curcat;
			goodsdata = data;
			console.log(data);//调试用
			for(var i=0;i<data.length; i++){  //这里不能用foreach 原因不明
				curcat = $('.one-category[cateid=' + data[i].categoryid +']');
				var newdish = dish.clone(true);
				newdish.css("display","inline-block");
				newdish.children("img").attr("src", data[i].photo);
				newdish.attr("goodsid", data[i].goodsid);
				newdish.find(".dish-name").children("span").text(data[i].name);
				newdish.attr("goodsid", data[i].sampleid);
				newdish.find(".dish-desc").text(data[i].dtldesc);
				newdish.find(".more-desc .tooltip-content").text(data[i].dtldesc);
				newdish.find(".star-wrapper .icon-stars").attr("title", "评分" + data[i].rate + "分").css("width", (data[i].rate/5)*100 + "%");
				newdish.find(".ratenumber").text(data[i].ratecount);
				newdish.find(".sells").text(data[i].monthlysold);
				newdish.find(".price").html('<i class="icon-cny"></i>' + data[i].price);
				if(data[i].spec==0){
					newdish.append(btnjoincart.clone(true));
				}else if(data[i].spec==1){
					newdish.append(btnspec.clone(true));
				}
				
				newdish.appendTo(curcat);				
			}
			clearCartitem();
			refreshShopCart();		
			loadShopCart();
			ValidateWindowScroll();
			validateCateClick();
		}	
		
		var menuLoader = function(data){
			console.log(data);//调试用
			var onecat = $(".one-category").eq(0);
			onecat.html('<h2 class="category">' + data[0].name + '<span class="category-hint">'+data[0].note+'</span> </h2><br />');
			$(".shop-category").html("").append($('<a href="javascript:;" class="active">' + data[0].name + '</a>'));
			onecat.attr("cateid", data[0].id);
			for(var i=1;i<data.length; i++){
				$(".shop-category").append($('<a href="javascript:;">' + data[i].name + '</a>'));
				copy = onecat.clone(true).attr("cateid", data[i].id).html('<h2 class="category">' + data[i].name + '<span class="category-hint">'+data[i].note+'</span> </h2><br />');
				copy.appendTo($('.shop-menu'));
			}
			requestGoods();
		}
	
		var cloneDish = function(){
			for(var i=0; i<7; i++){
				var newdish = dish.clone(true);
				//newdish
				newdish.appendTo(dish.parent());
			}
			var one = $(".one-category").eq(0);
			one.after(one.clone(true));
		}
		
		var ValidateWindowScroll = function(){
			onscroll = window.setInterval(OnScroll, 300);
			calcTopOffset();
		}
		
		var calcTopOffset = function(){
			
			var arr = $(".one-category");
			topoffs = new Array()
			 for(var i = 0;i< arr.length; i++){
			 	a = arr.eq(i);
			 	topoffs[i] = a.offset().top;
//			 	console.log(a.offset().top);
			 }
		}
		
		var ValidateBackToTop = function(){
			$(".return-to-top").click(function(){
				$("html body").animate({scrollTop: "0px"}, {speed: 500, easing: "linear"});
			});
		}
		
		var validateCateClick = function(){
			$(".shop-category a").click(function(){
				idx = $(".shop-category a").index(this);
				$("html body").animate({scrollTop: topoffs[idx]}, {speed: 300, easing: "linear"});
			})
		}
		
		var OnScroll = function(){
			var stop = $(window).scrollTop();

			if( !fixclone && (stop > ftop)){
				fixclone = fix.clone(true);
				fix.before(fixclone);
				fixclone.addClass("fixed-category");
			}else if(fixclone && (stop < ftop)){
				fixclone.remove();
				fixclone = null;
			}
			
			if(fixclone){
				fixclone.find("a").removeClass("active");
				
				for(var i =topoffs.length-1; i>=0; i--){
					if(stop+fixclone.height()>topoffs[i]){
						
						fixclone.find("a").eq(i).addClass("active");
						break;
					}
				}
			
				if(!fixclone.find("a").hasClass("active")){
					fixclone.find("a").eq(0).addClass("active");
				}
			
			}
		}
		
		

		
		//改变菜品实际显示模式
		var switchList = function(){
			$(".one-dish").toggleClass("dish-half");
			$(".one-dish").toggleClass("dish-full");
		}
		
		//点击切换菜品的显示模式响应事件
		var OnListClick = function(){
			if(!$(this).hasClass("active")){
				$(".display-type").toggleClass("active");
				switchList();
			}
			
		}
		
		
		/* 
		 * 加入购物车按钮系列响应事件 
		 * 
		 * 
		 */
		var bindJoinCartEvent = function(){
			btnjoincart.click(function(){
				var onedish = $(this).parent();
				var goodsid = parseInt($(this).parent(".one-dish").attr("goodsid"));
				var goodsname = $(this).siblings(".dish-name").children("span").text();
				var spec = 0;
				var price = parseFloat($(this).parents(".one-dish").find(".price").text());
				animateJoinCart();
				addToCart(shopid, goodsid, 1, goodsname, spec, price);
				$(this).after(btnmodnum.clone(true));
				$(this).remove();
				refreshShopCart();
			})
		}
		
		var validateSpec = function(){
			btnspec.click(function(){
				var gid = $(this).parents(".one-dish").attr("goodsid");
				var goodsname = $(this).parents(".one-dish").find(".dish-name").children("span").text();
				sspec.attr("goodsid", gid).attr("goodsname", goodsname);
				var str = '<dt>规格</dt>';
				curspec = [];
				for(i=0; i<speclist.length; i++){
					if(speclist[i].goodsid==gid)                                                                                                                                                                                                                                                                                                                                                                                                                                         
						curspec.push(speclist[i]);
				}
				str = str + '<dd specno=' + curspec[0].specno + ' class="active">' + curspec[0].specname + '</dd>';
				for(i=1;i<curspec.length;i++){
					str = str + '<dd specno=' + curspec[i].specno + '>' + curspec[i].specname + '</dd>';
				}
				sspec.find(".speclist").html(str);
				$(".s-spec .price").html('<i class="icon-cny"></i>' + curspec[0].price.toFixed(2));
					
				validateSpecDDClick();
				$(".s-spec-bck").css("display", "block");
				sspec.css({"display":"block", "left":$(this).offset().left+$(this).width() + 20, "top": $(this).offset().top -20});
				
			})
		}
		
		var validateSpecDDClick = function(){
			$(".speclist").children("dd").click(function(){
				$(".speclist dd").removeClass("active");
				$(this).addClass("active");
				$(".s-spec .selected").text($(this).text());
				c = findSpec(parseInt($(this).attr("specno")));
				$(".s-spec .price").html('<i class="icon-cny"></i>' + c.price.toFixed(2));
			});
			
		}
		
		var validateSpecSubmitClick = function(){
			$(".s-spec .spec-joincart").click(function(){
				var gid = parseInt($(".s-spec").attr("goodsid"));
				var gname = $(".s-spec").attr("goodsname");
				c = findSpec(parseInt($(".s-spec").find("dd.active").attr("specno")));
				addToCart(shopid, gid, 1, gname, c.specno, c.price);	
				
				sspec.css("display", "none");
				$(".s-spec-bck").css("display", "none");
				refreshShopCart();
				loadShopCart();
			});
			$(".s-spec .spec-cancel").click(function(){
				sspec.css("display", "none");
				$(".s-spec-bck").css("display", "none");
			});
		}
		
		var validateNumModifier = function(){
			btnmodnum.find(".minus").click(function(){
				var goodsid = parseInt($(this).parents(".one-dish").attr("goodsid"));
				var goodsname = $(this).parents(".one-dish").find(".dish-name").children("span").text();
				addToCart(shopid, goodsid, -1);
				refreshShopCart();
				loadShopCart();
				
			});
			btnmodnum.find(".plus").click(function(){
				var goodsid = parseInt($(this).parents(".one-dish").attr("goodsid"));
				addToCart(shopid, goodsid, 1);	
				$(this).siblings(".inputnumber").val(parseInt($(this).siblings(".inputnumber").val())+1);
				refreshShopCart();
			})
			btnmodnum.find(".inputnumber").change(function(){
				var num = $(this).val();
				if(!checkNumInput(num)){
					loadShopCart();
					return;
				};
				var goodsid = parseInt($(this).parents(".one-dish").attr("goodsid"));
				modCartNum(shopid, goodsid, parseInt(num));
				refreshShopCart();
			})
		}
		
		var checkNumInput = function(num){
			var regex = /\d{1,3}/;
			return regex.test(num);
		}
		
		var animateJoinCart = function(){
			var end = $(".cart-foot").find(".icon-cart").offset();
		    var flyer = $("<div class='fly-cart'></div>");
		    flyer.fly({  
		        start: {  
		            left: event.screenX,  
		            top: event.screenY-100  
		        },  
		        end: {  
		            left: end.left - $(window).scrollLeft(),  
		            top: end.top - $(window).scrollTop(),  
		            width: 20,  
		            height: 20  
		        },  
		        onEnd: function () {  
		            $('.end').css({  
		                background: 'red'  
		            });  
		            setTimeout(function () {  
		                $('.end').css({  
		                    background: 'blue'  
		                });  
		            }, 200);  
		            flyer.remove();  
		        }  
		    }); 			
		}

		
		//购物车界面控制
		
		var validCartPanelbtn = function(){
			//cartitem.click(function(){alert(1);})
			cartitem.find(".plus").click(function(){
				gid = parseInt($(this).parents(".cart-item").attr("goodsid"));
				addToCart(shopid, gid, 1);
				refreshShopCart();
				loadShopCart();
			});
			cartitem.find(".minus").click(function(){
				gid = parseInt($(this).parents(".cart-item").attr("goodsid"));
				addToCart(shopid, gid, -1);
				refreshShopCart();
				loadShopCart();
			});
			cartitem.find(".number").change(function(){
				num = parseInt($(this).val());
				if(!checkNumInput(num)) {
					refreshShopCart();
					return;
				}
				gid = parseInt($(this).parents(".cart-item").attr("goodsid"));
				modCartNum(shopid, goodsid, num);
				refreshShopCart();
				loadShopCart();
			});
			$(".cart-head .clear-cart").click(function(){
				clearCart();
				clearCartitem();
				loadShopCart();
			})
		}

		var refreshShopCart = function(){
			var cart = readCart();
			var sum;
			if(!cart){
				clearCartitem();
				return;
			}
			var items = $(".cart-item");
			for(i=0;i<items.length;i++){
				items.get(i).bvalid = false;
			}			
			for(i=0;i<cart.dtls.length;i++){
				bFlag = false;
				sum += cart.dtls[i].total;
				for(j=0;j<items.length;j++){
					item = items.eq(j);
					if(cart.dtls[i].goodsid == parseInt(item.attr("goodsid"))){
						if(parseInt(item.find(".number").val()) != cart.dtls[i].qty){
							item.find(".number").val(cart.dtls[i].qty);
							item.find(".price").html('<i class="icon-cny"></i>' + cart.dtls[i].total);
						}
						bFlag = true;
						item.get(0).bvalid = bFlag;
					}
					
				}
				if(!bFlag){
					gdidx = goodsdata.findIndex(function(a){
						return a.goodsid === cart.dtls[i].goodsid
					});
					if(gdidx>=0){
						gd = goodsdata[gdidx];
						item = cartitem.css("display", "block").clone(true);
						item.find(".cart-item-name").text(gd.name);
						item.attr("goodsid", cart.dtls[i].goodsid);
						item.find(".number").val(cart.dtls[i].qty);
						item.find(".price").html('<i class="icon-cny"></i>' + cart.dtls[i].total);
						item.get(0).bvalid = true;
						addCartItem(item);
					}
				}
			}
			for(i=0;i<items.length;i++){
				if(!items.get(i).bvalid){
					delCartItem(items.eq(i));
				}
			}
			sumShopCart();
		}
		
		var clearCartitem = function(){
			$(".cart-item").remove();
			sumShopCart();
		}
		
		var addCartItem = function(item){
			item.appendTo($(".cart-body"));
			item.css("display", "block");
		}
		
		var delCartItem = function(item){
			item.remove();
		}
		
		var sumShopCart = function(){
			var sum =0, num =0, lowest = parseFloat($(".minimum-charge").text());
			$(".cart-item").each(function(){
				console.log($(this).find(".price").text());
				sum += parseFloat($(this).find(".price").text());
			})
			num = $(".cart-item").length;
			$(".cart-foot .cart-total-count").text(num);
			if(num>0) $(".cart-foot .cart-total-count").css("display", "inline-block")
			else  $(".cart-foot .cart-total-count").css("display", "none");
			$(".cart-foot .cart-total-sum").html('<i class="icon-cny"></i>'+sum);
			if (num>0){
				if(sum>= lowest){
					$(".cart-foot .gotopay").removeClass("empty").addClass("full").text("去结算>").on("click",function(){
						window.location.href="//localhost:8080/eleme/savecart";
					});
				}else{
					$(".cart-foot .gotopay").removeClass("full").addClass("empty").text('还差' + (lowest-sum) +'元起送').off("click");
				}
			}else{
				$(".cart-foot .gotopay").removeClass("full").addClass("empty").text('购物车是空的').off("click");
			}
			console.log(cartitem.get(0).style.height);
			$(".cart-body").animate({height: (num  * cartitem.get(0).style.height)}, 1000);
		}
		
		var loadShopCart = function(){
			var idx=-1;
			var items = $(".shop-menu .one-dish");
			for(i=0;i<items.length;i++){
				spec = 0;
				gid = items.eq(i).attr("goodsid");
				gdx = goodsdata.findIndex(function(a){
					return a.goodsid === parseInt(gid);
				});
				if(gdx>=0) spec = goodsdata[gdx].spec;
				btn = items.eq(i).find(".cartbutton");
				if(spec==0)
					btn.after(btnjoincart.clone(true))
				else
					btn.after(btnspec.clone(true));
				btn.remove();
			}			
			var cart = readCart();
			if(!cart) return;
			for(i=0;i<cart.dtls.length;i++){
				for(j=0;j<items.length;j++){
					item = items.eq(j);
					item.get(0).bfound = true;
					if(parseInt(item.attr("goodsid")) == cart.dtls[i].goodsid){
						btn = item.find(".cartbutton").eq(0);
						abtn = btnmodnum.clone(true);
						abtn.find(".inputnumber").val(cart.dtls[i].qty);
						btn.after(abtn);
						btn.remove();
						break;
					}
				}
			}

//			validateNumModifier();
		}
		//购物车结束

		var validChangeDisType = function(){
			$(".display-type").click(
				function(){
					if(!$(this).hasClass("active")){
						$(".display-type").toggleClass("active");
						switchList();
						calcTopOffset();  //重新计算分类高度
					}
				});
		}
		
		var clickEventHooker = function(){
			validateDescHover();		//生效鼠标移动到商品详细时浮现提示框的事件
			validateShowTipHover();		//生效其他浮现提示框
			validChangeDisType();		//生效切换商品显示模式按钮
			ValidateBackToTop();		//生效回到顶部按钮
			validateShopGuideHover();	//生效悬停显示门店详情
			bindJoinCartEvent();		//加入购物车按钮响应事件
			validateSpec();				//选规格按钮响应事件
			validateSpecSubmitClick();	//选规格窗口 提交和取消
			validateNumModifier();
			validCartPanelbtn();
		}
		
		function jsontest(){
			var res = JSON.parse('{"id":1}');
			console.log(JSON.stringify(res));
		}
		
		return {
			run: function(){
				
				clickEventHooker();
				requestSpec();
				requestMenu();
				//cloneDish();
				

			},
			pubf: {
				
			}
		}
	}();
	
	main.run();
	window.js = main.pubf;
	
})(jQuery);
